$(function(){
    circlefile.init();
});

var circlefile = {
    cons : {
		num_max_tag 		: 	8,
		num_max_recent_posts:   4,
		num_max_recent_galaxies:   4
	},

    init:function(){
        render_top_bar();
        circle_basicInfo();
        var user_info_block = $('#profile-container .status-block');
		get_user_info(user_info_block);
        var tagged_nebulas = $('.nebulas-block');
        circle_taggedNebulas(circlefile.cons.num_max_tag,tagged_nebulas);
        var recent_post = $('.recent-post ul');
        circle_recentPost(circlefile.cons.num_max_recent_posts,recent_post,circle_uid);
        var recent_galaxy = $('.recent-galaxy ul');
        circle_recentGalaxy(circlefile.cons.num_max_recent_galaxies,recent_galaxy,circle_uid);


    },

    render:function(template, params){
        var arr = [];
        switch(template){
            case 'user-info':
                if(params['avatar']==0)
                    params['avatar']="./img/noavatar_small.gif";
                arr = [
                    '<div style="padding: 2px; width:169px; height: 169px;" class="avatar-area">',
                    '<img style="display:none" src="',params['avatar'],'"/></div>',
                    '<span style="text-align: center; margin: 5px 0 5px 0;">',params['username'],'</span>'
                ];
                break;
            case 'tag-nebulas':
                var length = 120;
				var proc_string = params['description'];
                if(proc_string==undefined)
                    proc_string=" ";
				if(proc_string.length>length){
					proc_string = proc_string.substring(0, length);
					proc_string = proc_string + "...";
				}
				arr = [
					'<div class="nebula-record" style="width:200px;"><span class="icon"><a href="./topics.php?nid=',params['nid'],'"><img style="width: 50px; height: 50px;"',
					,'src="',params['icon'],
					'"/></a></span><div class="content" style="height:80px; width:150px;"><span class="name" style="width:150px;"><a href="./topics.php?nid=',params['nid'],'">',params['name'],'</a>',
					'</span><div class="desc" style="height:60px; width:150px;">',proc_string,'</div></div></div>'

				];
                break;
            case 'recent-post':
                var length = 100;
				var proc_string = htmlDecode(params['body']);
                //uncount the tag content
                length += extentPostLength(proc_string);               
				if(proc_string.length>length){
					proc_string = proc_string.substring(0, length);
					proc_string = proc_string + "...";
				}
                //modify author's avatar
                if(params['avatar']==0)
                    params['avatar']= "./img/noavatar_small.gif";
				arr=[
					'<li><div class="left"><div class="avatar-area" style="height:50px;width:50px"><img style="display:none"',
                    'src="',params['avatar'],'"/></div></div>',
					'<div class="right"><span class="title"><a href="./topics.php?nid=',params['default_nid'],'&pid=',params['pid'],'">',params['title'],'</span></a><span class="content">',proc_string,
					'</span><span class="end"><div class="type type-post">Post</div>posted by <a href="./circlefile.php?uid=',params['post_uid'],'">', params['username'],'</a> ',params['ts'],'</span></div></li>'
				];
				break;
            case 'recent-galaxy':
                arr = [
                    '<li><div class="left"><div class="avatar-area" style="height:50px;width:50px"><img style="display:none"',
                    'src="',params['avatar'],'"/></div></div>',
					'<div class="right"><span class="title"><a>',params['title'],'</span></a><span class="content">',params['description'],
					'</span><span class="end"><div class="type type-galaxy">Galaxy</div>created by <a href="./circlefile.php?uid=',params['galaxy_uid'],'">', params['username'], '</a> ',params['ts'],'</span></div></li>'
                ];
                break;
            case 'user-circle':
                
                if(params['circled']=='0')
                    arr = ['<div class="roundedS new-bt circle-fun" style="">Circle</div>'];
                else if(params['circled']=='1')
                    arr = ['<div class="roundedS new-bt uncircle-fun" style="">Un-circle</div>'];
                else
                    alert('circle bt error');
                break;
            case 'circle-content':
                arr = [
                    '<div class="tri-down"></div><div class="common-nebula roundedS">Choose which common nebulas you want to put: ',
                    '<div class="common-list"></div><div class="confirm-area" style=',
                    '"float:right;margin-top:25px;font-size:15px;"></div></div>'
                ];
                break;
            case 'common-items':
                arr = [
                    '<p><img id="com_',params['nid'],'" class="common-item" title="',params['name'],'" name="unselect" src="',params['icon'],'"/></p>'
                ]
                break
        }
        return arr.join('');
    }

}
function circle_basicInfo(){
    $('#profile-container').css('display','none');
    $.ziGET('getUser',{'uid':circle_uid},function(r){
        var user_avatar = circlefile.render('user-info',r[0]);
        $('.avatar').html(user_avatar);
        $('#view-name').html('About ' + r[0]['username']);
        //resize avatar
        var avatarImg = $('.avatar .avatar-area img');
        if(avatarImg.length>0)
            reSizeAvatar(avatarImg);
        //add circle button if user view other's profile
        if(session_user_info['uid']!=circle_uid){
            var circleBt = circlefile.render('user-circle',r[0]);
            $('.circle-block').html(circleBt);
        }
        //bind un/circle function
        circle_action(r);
        uncircle_action(r);
        $('#profile-container').css('display','block');
    })
}
function uncircle_action(r){
    var uncircleFunObj = $('.uncircle-fun');
    uncircleFunObj.unbind('click');
    uncircleFunObj.bind('click',function(){
        var actionBt = $('.circle-block .new-bt');
        actionBt.html('Requesting...');
        $.ziGET('uncircle_all_nebulas',{'uid_to':circle_uid},function(r){
            actionBt.removeClass('uncircle-fun');
            actionBt.addClass('circle-fun');
            actionBt.html('Circle');
            //bind circle action
            circle_action(r);
        });
    })
}
function circle_action(r){
    var circleFunObj = $('.circle-fun');
    circleFunObj.unbind('click');
    circleFunObj.bind('click',function(){
        $('.circle-content').html('');
        var circleContent = circlefile.render('circle-content', r[0]);
        $('.circle-content').html(circleContent);
        //content list
        var contentList = $('.common-list');
        contentList.html('<div style="padding-top:10px;">loading...</div>');
        $.ziGET('get_common_nebulas',{
            'uid_to': circle_uid
        },function(k){
            contentList.html('');
            if(k!=undefined){
                for(var j=0;j<k.length;j++){
                    var commonItem = circlefile.render('common-items',k[j]);
                    contentList.append(commonItem);
                }
                //bind select action
                var commonObj = $('.common-item');
                commonObj.unbind('click');
                commonObj.bind('click',function(){
                    var selected = $(this).attr('name');
                    if(selected=="unselect"){
                        $(this).css('border', '1px solid red');
                        $(this).addClass('selected');
                        $(this).attr('name','select');
                    }
                    else if(selected=="select"){
                        $(this).css('border', '1px solid #DDD');
                        $(this).removeClass('selected');
                        $(this).attr('name','unselect');
                    }
                    else
                        alert('select name error');
                });
                $('.confirm-area').html('<input id="confirm-yes" type="button" value="Yes" style="width:30px;color:#777"/><input id="confirm-no" type="button" value="No" style="width:30px;color:#777">');
                //bind confirm action
                $('#confirm-yes').unbind('click');
                $('#confirm-yes').bind('click',function(){
                    var selectItems = $('.common-list .selected');
                    if(selectItems.length>0){
                        $('.circle-content').hide();
                        var actionBt = $('.circle-block .new-bt');
                        actionBt.html('Requesting...');
                        actionBt.removeClass('circle-fun');
                        selectItems.each(function(index){
                            var nid = $(this).attr('id');
                            var splitIndex = nid.indexOf('_');
                            nid = nid.substring(splitIndex+1);
                            $.ziGET('circle',{
                                'uid_to' : circle_uid,
                                'nid' : nid
                            }, function() {
                                if(index+1==selectItems.length){
                                    actionBt.addClass('uncircle-fun');
                                    actionBt.html('Un-circle');
                                    //bind uncircle action
                                    uncircle_action(r);
                                }
                            });
                        });                        
                    }
                    else{
                       alert('You must select at least one common nebula');
                    }
                });
                $('#confirm-no').unbind('click');
                $('#confirm-no').bind('click',function(){
                    $('.circle-content').html('');
                });
            }
            else{
                contentList.html('<div style="padding-top:10px">No common nebula</div>');
                contentList.append('<input id="confirm-ok" type="button" value="ok" style="float:right;width:40px;color:#777"/>');
                $('#confirm-ok').unbind('click');
                $('#confirm-ok').bind('click',function(){
                    $('.circle-content').html('');
                })
            }
        });
    })
}
function circle_taggedNebulas(num,target){
    target.html('<div class="section-paddingL loading"><img src="img/loading.gif"/></div');
    $.ziGET('nebulas_for_uid', {'uid':circle_uid}, function(r) {
		var markup="";
		num = Math.min(num, r.length);
        for(var i = 0; i < num; i++) {
            var markup = markup + circlefile.render('tag-nebulas', r[i]);
        }
        target.html(markup);
        if(r.length>num){
            target.find($('.showall')).html("Show all");
        }
        if(num == 0){
            target.html('<div class="section-padding" style="text-align: center;">No tagged Nebula</div>')
        }
	});
}

function circle_recentPost(num, contentBlock, uid){
    contentBlock.html( '<div class="loading section-padding"><img src="img/loading.gif"/></div>' );
	$.ziGET('recent_posts', {'max_num':num,'uid':uid}, function(r) {
        var markup="";
        for(var i = 0; i < r.length; i++) {
            markup = markup+circlefile.render('recent-post', r[i]);
        }
        if(r.length==0){
            markup = '<div class="section-padding" style="text-align: center;">No viewed post</div>';
        }
        contentBlock.html(markup);
        //resize img
        var imgTag = $('.recent-post .content img');
        if(imgTag.length>0)
            reSizeImg(imgTag);
        //resize author avatars
        var postAvatars = $('.recent-post .avatar-area img');
        if(postAvatars.length>0)
            reSizeAvatar(postAvatars);
	});
}

function circle_recentGalaxy(num,contentBlock,uid){
    contentBlock.html( '<div class="loading section-padding"><img src="img/loading.gif"/></div>' );
	$.ziGET('recent_galaxies', {'max_num':num,'uid':uid}, function(r) {
        var markup="";
        for(var i = 0; i < r.length; i++) {
            markup = markup+circlefile.render('recent-galaxy', r[i]);
        }
        if(r.length==0){
            markup = '<div class="section-padding" style="text-align: center;">No viewed galaxy</div>'
        }
        contentBlock.html(markup);

        //resize author avatars
        var galaxyAvatars = $('.recent-galaxy .avatar-area img');
        if(galaxyAvatars.length>0)
            reSizeAvatar(galaxyAvatars);
	});
}